<?php 
class NewsletterController extends DomController {
	
	public function index() {
		
	}
	
	// ----------------------------------------------
	// Newsletters handling
	// ----------------------------------------------
	
	public function newsletters() {
	
		if( $_GET['delete'] && $item = Newsletter::load( $_GET['delete'] )){
			$item->delete();
		}
						
		$source = new DomArDataSource( Newsletter::query()->orderBy('t.createdTime DESC'), 100 );
		
		$panel = array(
			'title' => 'Uudiskirjad',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 1,
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus',
					'link' => $this->getUrl('newsletter/'),
				),
				array(
					'id' => 'newslettersList',
					'type' => 'grid',
					'source' => $source,
					'fields' => array(
						array('key' => 'name', 'title' => 'Nimi'),
						array('key' => 'createdTime', 'title' => 'Loodud'),
						array('key' => 'template', 'title' => 'Templaat'),
						array('key' => 'fromName', 'title' => 'Kellelt'),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('newsletter/'), 'title' => 'Valikud','colspan' => 2),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('newsletters/&delete='), 'confirmMessage' => 'Are you sure?' ),
					),
				),
			),
		);
					
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function newsletter( $id = NULL ) {
		$new = $id == 0;
		$item = $new ? new Newsletter() : Newsletter::load($id);
				
		$post = DomFgPost::getInstance();
		
		if( $post->doAddBlocks ) {
			for( $i=0; $i<$post->addBlocks; $i++ ) {
				
				switch( $post->addBlocksType ) {
					case 'basic':
						$block = new NewsletterBlock_Basic();
					break;
					case 'html':
						$block = new NewsletterBlock_Html();
					break;
					default:
						throw new RuntimeException('Unknown block type!');
					break;
				}
				$item->blocks[] = $block;
			}
			$item->save();
		}
		
		if( $_GET['deleteBlock'] && $block = $item->blocks->find($_GET['deleteBlock']) ) {
			$block->delete();
		}
		
		if( $_GET['deleteImage'] && $block = $item->blocks->find($_GET['deleteImage']) ) {
			$block->image->unlink();
			$block->save();
		}
		
		if( $post->save ) {
			$item->name = $post->name;
			$item->template = $post->template;
			$item->subject  = $post->subject;
			$item->fromName  = $post->fromName;
			$item->fromEmail  = $post->fromEmail;
		}
		
		if( $post->sendSample ) {
			$mail = $item->getPreparedMail();
			$mail->addAddress( $post->sampleEmail, $post->sampleName );
			if( $mail->Send() ) {
				$sendSampleMessage = array('type' => 'ok','colspan' => 5,'message' => 'Email saadetud',);
			} else {
				$sendSampleMessage = array('type' => 'error','colspan' => 5,'message' => 'Saatmine ebaõnnestus: '.$mail->ErrorInfo,);
			}
		}
		
		if( $post->saveBlocks ) {
			
			foreach( $item->blocks as $block ) {
				
				$block->order = (int)$post->order[$block->id];
				
				switch( get_class($block) ) {
					case 'NewsletterBlock_Basic':
						
						$block->title = $post->title[$block->id];
						$block->readMoreLink = $post->readMoreLink[$block->id];
						$block->contents = $post->contents[$block->id];
						$block->image->addUploaded( $post->newImage[$block->id][0], $post->newImage[$block->id][1]);
						$block->imagePosition = $_POST['imagePosition'][$block->id];
		
						if( $post->resizeImage[$block->id][0] > 0 ) {
							$r = $post->resizeImage[$block->id];
							$block->image->resize( $r[0], $r[1] );
						}
					break;
					case 'NewsletterBlock_Html':
						$block->contents = $post->contents[$block->id];
					break;
				}
				
			}
		}
		
		if( $post->save or $post->saveBlocks ) {
			if( $item->save() ) {
				$id = $item->id;
				$message = array('type' => 'ok','colspan' => 2,'message' => 'Salvestatud',);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'title' => 'Uudiskiri',
			'layout' => 'table',
			'action' => $this->getUrl('newsletter/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Nimi',
					'value' => $item->name,
					'name' => 'name',
					'style' => 'width:500px;',
				),
				array(
					'title' => 'Templaat',
					'type' => 'select',
					'values' => Newsletter::getTemlatesList(),
					'name' => 'template',
					'selected' => $item->template,
				),
				array(
					'type' => 'textField',
					'title' => 'Subjekt',
					'value' => $item->subject,
					'name' => 'subject',
					'style' => 'width:500px;',
				),
				array(
					'type' => 'textField',
					'title' => 'Kellelt (nimi)',
					'value' => $item->fromName,
					'name' => 'fromName',
					'style' => 'width:500px;',
				),
				array(
					'type' => 'textField',
					'title' => 'Kellelt (email)',
					'value' => $item->fromEmail,
					'name' => 'fromEmail',
					'style' => 'width:500px;',
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta üldinfo',
					'name' => 'save'
				),
				( $item->id == 0 ? NULL : array(
					'target' => '_blank',
					'title' => 'Vaata emaili vaadet',
					'link' => $this->getUrl('emailView/'.$id)
				)),
			),
		);
		
		if( $item->id > 0 ) {
		$samplePanel = array(
			'id' => 'samplePanel',
			'title' => 'Saada näidis',
			'layout' => 'table',
			'closable' => true,
			'closed' => (bool)!$post->sendSample,
			'action' => $this->getUrl('newsletter/'.$id),
			'layoutConfig' => array(
				'columns' => 5,
				'columnWidths' => array(80,220,80,220),
			),
			'items' => array(
				$sendSampleMessage,
				array(
					'type' => 'textField',
					'name' => 'sampleEmail',
					'title' => 'E-mail',
				),
				array(
					'type' => 'textField',
					'name' => 'samleName',
					'title' => 'Nimi',
				),
				array(
					'type' => 'button',
					'title' => 'saada',
					'value' => 'Saada näidis',
					'name' => 'sendSample',
				),
			),
		);
		
		$blocksPanel = array(
			'title' => 'Blokid',
			'layout' => 'table',
			'action' => $this->getUrl('newsletter/'.$id),
			'layoutConfig' => array(
				'columns' => 5,
				'columnWidths' => array( 150,200 ),
			),
			'items' => array(
				array(
					'type' => 'select',
					'values' => intArray(1,10),
					'name' => 'addBlocks',
					'title' => 'Lisa blokke',
				),
				array(
					'type' => 'select',
					'values' => NewsletterBlock::getBlocksList(),
					'name' => 'addBlocksType',
					'title' => 'Tüüp',
				),
				array(
					'type' => 'button',
					'name' => 'doAddBlocks',
					'title' => 'Lisa',
				),
				array(
					'type' => 'separator',
					'title' => 'Olemasolevad blokid',
					'colspan' => 5,
				),
			),
		);
		
		foreach( $item->blocks->query()->orderBy('t.order')->commit() as $block ) {
			if( $block instanceof NewsLetterBlock_Basic ) {
				$blocksPanel['items'][] = $this->getBlockForm_Basic( $block );
			} else if( $block instanceof NewsLetterBlock_Html ) {
				$blocksPanel['items'][] = $this->getBlockForm_Html( $block );
			}
		}
		}
		$this->view->contents = DomFg::render( $panel ) . DomFg::render($samplePanel) . DomFg::render( $blocksPanel );
		
	}
	
	public function getBlockForm_Basic( NewsLetterBlock_Basic $item ) {
		
		$templateSelection = new DomView( '/'.Newsletter::ADMIN_TEMPLATES_DIR . 'templateSelection.html'  );
		$templateSelection->imagesUrl = $this->getMediaUrl( Newsletter::ADMIN_TEMPLATES_DIR );
		$templateSelection->location = $item->imagePosition;
		$templateSelection->id = $item->id;
		$templateSelection = $templateSelection->fetch();
		
		$blocksPart = array(
			'type' => 'panel',
			'colspan' => 5,
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 6,
				//'border' => 1,
				'columnWidths' => array(),
			),
			'border' => true,
			'frame' => false,
			'items' => array(
				array(
					'colspan' => 3,
					'type' => 'value',
					'value' => $templateSelection,
				),
				array(
					'type' => 'number',
					'name' => 'order['.$item->id.']',
					'value' => $item->order->pos,
					'title' => 'Järjekorra number',
				),
				array(
					'type' => 'button',
					'title' => 'Salvesta blokid',
					'name' => 'saveBlocks'
				),
				array(
					'type' => 'panel',
					'border' => false,
					'frame' => false,
					'rowspan' => 4,
					'colspan' => 2,
					'layout' => 'table',
					'layoutConfig' => array(
						'columns' => 3,
						'columnWidths' => array( ),
					),
					'items' => array(
						array(
							'colspan' => 3,
							'type' => 'image',
							'style' => 'width:260px; height:140px;',
							'src' => $item->image->getUrl(),
						),
					),
				),
				array(
					'type' => 'textField',
					'title' => 'Pealkiri',
					'value' => $item->title,
					'name' => 'title['.$item->id.']',
					'style' => 'width:500px;',
					'colspan' => 4,
				),
				array(
					'type' => 'textField',
					'title' => 'Loe veel link',
					'value' => $item->readMoreLink,
					'name' => 'readMoreLink['.$item->id.']',
					'style' => 'width:500px;',
					'colspan' => 4,
				),
				array(
					'type' => 'file',
					'title' => 'Pilt',
					'name' => 'newImage['.$item->id.']',
					'colspan' => 3,
				),
				array('type' => 'value'),
				array(
					'type' => 'button',
					'title' => 'Kustuta pilt',
					'link' => $this->getUrl('newsletter/'.$item->newsletter->id.'/&deleteImage='.$item->id),
					'confirmMessage' => 'Oled kindel, et soovid pildi kustutada?',
				),
				array(
					'type' => 'button',
					'title' => 'Kustuta blokk',
					'confirmMessage' => 'Oled kindel, et soovid bloki kustutada?',
					'link' => $this->getUrl('newsletter/'.$item->newsletter->id.'/&deleteBlock='.$item->id),
					'colspan' => 2,
				),
				array(
					'type' => 'htmlEditor',
					'value' => $item->contents,
					'name' => 'contents['.$item->id.']',
					'style' => 'width:500px; height:370px;',
					'colspan' => 6,
				),
				
			),
		);
		return $blocksPart;
	}
	
	public function getBlockForm_Html(NewsLetterBlock_Html $item) {
		
		$blocksPart = array(
			'type' => 'panel',
			'colspan' => 5,
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 6,
				//'border' => 1,
				'columnWidths' => array(),
			),
			'border' => true,
			'frame' => false,
			'items' => array(
				array(
					'colspan' => 3,
					'type' => 'value',
					'value' => $templateSelection,
				),
				array(
					'type' => 'number',
					'name' => 'order['.$item->id.']',
					'value' => $item->order->pos,
					'title' => 'Järjekorra number',
				),
				array(
					'type' => 'button',
					'title' => 'Salvesta blokid',
					'name' => 'saveBlocks'
				),
				array(
					'type' => 'button',
					'title' => 'Kustuta blokk',
					'confirmMessage' => 'Oled kindel, et soovid bloki kustutada?',
					'link' => $this->getUrl('newsletter/'.$item->newsletter->id.'/&deleteBlock='.$item->id),
					'colspan' => 2,
				),
				array(
					'type' => 'htmlEditor',
					'value' => $item->contents,
					'name' => 'contents['.$item->id.']',
					'style' => 'width:500px; height:370px;',
					'colspan' => 6,
				),
				
			),
		);
		return $blocksPart;
	}
	
	public function webView( $id ) {
		$this->view->setTemplate(false);
		$item = Newsletter::load($id);
		echo $item->renderForWeb();
	}
	
	public function emailView( $id ) {
		$this->view->setTemplate(false);
		$item = Newsletter::load($id);
		echo $item->renderForEmail();
	}
	
	public function searchNewsletters( $search ) {
		
		$items = Newsletter::query()
			->where('t.name LIKE \'%' . addslashes($search) . '%\'')
			->orderBy('t.name DESC')
			->commit();
		
		$json = '[';
		foreach( $items as $item ) {
			$json .= "{";
			$json .= "'key':'" . addslashes($item['id']) . "',";
			$json .= "'value':'" . addslashes($item['name']) . "',";
			$json .= "},";
		}
		$json .= ']';
		die( $json );
			
	
	}
	
	// ----------------------------------------------
	// Lists handling
	// ----------------------------------------------
	
	public function emailLists() {
		
		if( $_GET['delete'] && $item = NewsletterList::load( $_GET['delete'] )){
			$item->delete();
		}
						
		$source = new DomArDataSource( NewsletterList::query()->orderBy('t.name DESC'), 40 );
		
		function countEmails( $row ) {
			return $row->emails->count();
		}
		
		$panel = array(
			'title' => 'List',
			'layout' => 'table',
			'style' => 'width:600px;',
			'layoutConfig' => array(
				'columns' => 1,
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus',
					'link' => $this->getUrl('emailList/'),
				),
				array(
					'id' => 'newsletterLists',
					'type' => 'grid',
					'source' => $source,
					'fields' => array(
						array('key' => 'name', 'title' => 'Nimi'),
						array('key' => 'createdTime', 'title' => 'Loodud'),
						array('handler' => 'countEmails', 'title' => 'Emaile'),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('emailList/'), 'title' => 'Valikud','colspan' => 2),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('emailLists/&delete='), 'confirmMessage' => 'Olete kindel, et soovite terve listi kustutada?' ),
					),
				),
			),
		);
					
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function emailList( $id = NULL ) {

		$new = $id == 0;
		$item = $new ? new NewsletterList() : NewsletterList::load($id);
				
		$post = DomFgPost::getInstance();
		
		if( $_GET['deleteEmail'] && $email = $item->emails->find($_GET['deleteEmail']) ) {
			$email->delete();
		}
		
		if( $_GET['swapActive'] && $email = $item->emails->find($_GET['swapActive']) ) {
			$email->active = !$email->active;
			$email->save();
		}
		
		if( $post->deleteEmails ) {
			foreach( (array)$post->email as $id ) {
				$s = $item->emails->find($id);
				if( $s ) {
					$s->delete();
				}
			}
			unset($s);
		}
		
		if( $post->addEmails ) {
			$result = $item->importFromCsv( $post->addEmailsCsv );

			$messageStart  = '
				Lisati <b>'.$result['added'].'</b> uut emaili.<br />
				Lisamata jäeti <b>'.$result['existing'].'</b>, kuna need juba olid andmebaasis.<br />';
			
			if( $result['errors'] > 0 ) {
				$addEmailsMessage = array('type' => 'warning','colspan' => 4,'message' => $messageStart.'
					Probleeme oli <b>'.$result['errors'].'</b> emailiga<br />
					<b>Probleemsed:</b><br />
					'.implode('<br />',$result['problematicEmails']).'
				');
			} else {
				$addEmailsMessage = array('type' => 'ok','colspan' => 4,'message' => $messageStart);
			}
		}
		
		if( $post->save ) {
			
			$item->name = $post->name;
			$item->comment = $post->comment;
			
			if( $item->save() ) {
				$id = $item->id;
				$message = array('type' => 'ok','colspan' => 4,'message' => 'Salvestatud',);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 4,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'title' => 'List',
			'layout' => 'table',
			'style' => 'width:800px',
			'action' => $this->getUrl('emailList/'.$id),
			'layoutConfig' => array(
				'columns' => 4,
				'columnWidths' => array( 150 ),
				//'border' => 1,
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Nimi',
					'value' => $item->name,
					'name' => 'name',
				),
				array(
					'type' => 'value',
					'title' => 'Loodud',
					'value' => $item->createdTime,
				),
				array(
					'type' => 'textArea',
					'style' => 'width:600px; height:60px;',
					'title' => 'Kommentaar',
					'name' => 'comment',
					'value' => $item->comment,
					'colspan' => 3,
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
		
		if( $item->id > 0 ) {
		$addPanel = array(
			'id' => 'addEmailsPanel',
			'title' => 'Lisa emaile',
			'closable' => true,
			'closed' => $post->addEmailsCsv == NULL ? true : false,
			'layout' => 'table',
			'style' => 'width:800px',
			'action' => $this->getUrl('emailList/'.$id),
			'layoutConfig' => array(
				'columns' => 4,
				'columnWidths' => array( 150 ),
				//'border' => 1,
			),
			'items' => array(
				$addEmailsMessage,
				array(
					'type' => 'textArea',
					'style'  => 'width:300px',
					'title' => 'Lisa emaile',
					'colspan' => 2,
					'name' => 'addEmailsCsv',
					'value' => $post->addEmailsCsv,
				),
				array(
					'type' => 'value',
					'rowspan' => 2,
					'value' => '
						<b>Lisamise formaat:</b> (CSV - comma seperated values) <br />
						Email_1,Nimi_1 <br />
						Email_2,Nimi_2<br />
						...<br />
						<b>Näide: </b><br />
						Kellegi.Nimi@mail.ee,Kellegi Nimi<br />
						Teine.Inimene@hotmail.com,Teine Inimene<br />',
				),
				array('type' => 'value'),
				array(
					'type' => 'button',
					'name' => 'addEmails',
					'title' => 'Lisa emailid',
					'colspan' => 2,
					'style' => 'float:right',
				),
			),
		);
		
		function active( $row ) {
			return $row->active ? '<b style="color:green">Jah</b>' : '<b style="color:red">Ei</b>';
		}
		
		function checkBox( $row ) {
			return DomFg::render(array(
				'type' => 'checkBox',
				'name' => 'email[]',
				'value' => $row->id,
				'checked' => false,
			));
		}
		
		$emailsPanel = array(
			'title' => 'Emailid',
			'layout' => 'table',
			'style' => 'width:800px',
			'action' => $this->getUrl('emailList/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				array(
					'id' => 'emailsGrid_'.$id,
					'type' => 'grid',
					'source' => new DomArDataSource( $item->emails->query()->orderBy('t.email DESC'), 100 ),
					'fields' => array(
						array('handler' => 'checkBox'),
						array('key' => 'email', 'title' => 'Email'),
						array('key' => 'name', 'title' => 'Nimi'),
						array('handler' => 'active', 'link' => $this->getUrl('emailList/'.$id.'/&swapActive='),'title' => 'Aktiivne'),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('editEmail/'), 'title' => 'Valikud','colspan' => 2),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('emailList/'.$id.'&deleteEmail='), 'confirmMessage' => 'Olete kindel, et soovite terve listi kustutada?' ),
					),
				),
			),
			'buttons' => array(
				array(
					'title' => 'Kustuta',
					'name' => 'deleteEmails',
					'style' => 'float:left',
				)
			),
		);

		}
		$this->view->contents = DomFg::render( $panel ) . DomFg::render($addPanel) . DomFg::render($emailsPanel);
		
	}
	
	public function editEmail( $id ) {
		$new = $id == 0;
		$item = $new ? new NewsletterEmail() : NewsletterEmail::load($id);
				
		$post = DomFgPost::getInstance();
		
		if( $post->save ) {
			
			$item->email = $post->email;
			$item->name = $post->name;
			$item->active = $post->active;
			
			if( $item->save() ) {
				$id = $item->id;
				$message = array('type' => 'ok','colspan' => 2,'message' => 'Salvestatud',);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'error','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'title' => 'Email',
			'layout' => 'table',
			'style' => 'width:500px;',
			'action' => $this->getUrl('editEmail/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message ,
				array(
					'type' => 'textField',
					'title' => 'Email',
					'value' => $item->email,
					'name' => 'email',
				),
				array(
					'type' => 'textField',
					'title' => 'Nimi',
					'value' => $item->name,
					'name' => 'name',
				),
				array(
					'type' => 'checkBox',
					'title' => 'Aktiivne',
					'checked' => $item->active,
					'name' => 'active',
				),
			),
			'buttons' => array(
				array(
					'title' => 'Tagasi',
					'link' => $this->getUrl('emailList/'.$item->list->id),
					'style' => 'float:left',
				),
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function searchEmailLists( $search ) {
		
		$items = NewsletterList::query()
			->where('t.name LIKE \'%' . addslashes($search) . '%\'')
			->orderBy('t.name DESC')
			->commit();
		
		$json = '[';
		foreach( $items as $item ) {
			$json .= "{";
			$json .= "'key':'" . addslashes($item['id']) . "',";
			$json .= "'value':'" . addslashes($item['name']) . "',";
			$json .= "},";
		}
		$json .= ']';
		die( $json );
			
	
	}
	
	// ----------------------------------------------
	// Send emails handling
	// ----------------------------------------------
	
	public function sends() {
		
		//NewsletterSend::getTable()->update();
		
		if( $_GET['delete'] && $item = NewsletterSend::load( $_GET['delete'] )){
			$item->delete();
		}
						
		$source = new DomArDataSource( NewsletterSend::query()->orderBy('t.startTime DESC'), 40 );
		
		function confirmed( $row ) {
			return $row->confirmed ? '<b style="color:green">Jah</b>' : '<b style="color:red">Ei</b>';
		}
		
		function sent( $item ) {
			if( $item->max == 0 ) {
				return 'Pole alustatud';
			} else {
			return '<div id="loader" style="padding:1px; margin:2px; float:left; border: 1px solid black; width:60px;">
		<div id="bar" style="width:'.(($item->sent+$item->errors) * 60 / $item->max).'px; height:7px; background-color:green;"></div>
	</div> '.round(($item->sent+$item->errors) * 100 / $item->max).'%';
			}
		}
		
		$panel = array(
			'title' => 'Saatmised',
			'layout' => 'table',
			'layoutConfig' => array(
				'columns' => 1,
			),
			'items' => array(
				array(
					'type' => 'button',
					'title' => 'Lisa uus',
					'link' => $this->getUrl('send/'),
				),
				array(
					'type' => 'grid',
					'source' => $source,
					'fields' => array(
						array('key' => 'startTime', 'title' => 'Algusaeg'),
						array('key' => array('newsletter','name'), 'title' => 'Uudiskiri'),
						array('key' => array('list','name'), 'title' => 'List'),
						array('handler' => 'confirmed', 'title' => 'Kinnitatud'),
						array('handler' => 'sent', 'title' => 'Saadetud', 'width' => 120),
						array('type' => 'gridButton', 'value' => 'Muuda', 'link' => $this->getUrl('send/'), 'title' => 'Valikud','colspan' => 2),
						array('type' => 'gridButton', 'value' => 'Kustuta', 'link' => $this->getUrl('sends/&delete='), 'confirmMessage' => 'Are you sure?' ),
					),
				),
			),
		);
					
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function send( $id = NULL ) {
		$new = $id == 0;
		$item = $new ? new NewsletterSend() : NewsletterSend::load($id);
				
		$post = DomFgPost::getInstance();
		
		if( $post->save or $post->saveAndSend) {
			
			$item->comment = $post->comment;
			$item->startTime = $post->startTime;
			$item->confirmed = (bool)$post->confirmed;
			$item->newsletter = Newsletter::load($post->newsletter);
			$item->list = NewsletterList::load($post->list);
			
			if( $item->save() ) {
				if( $post->saveAndSend ){
					$this->goToSection('sender/'.$item->id);
				}
				
				$id = $item->id;
				$message = array('type' => 'ok','colspan' => 2,'message' => 'Salvestatud',);
			} else {
				$message = array('message' => 'Tekkinud on viga!','type' => 'ok','colspan' => 2,'description' => implode('<br>',$item->getValidationReport()->messages),);
			}
		}
				
		$panel = array(
			'style' => 'width:500px',
			'title' => 'Saatmine',
			'layout' => 'table',
			'action' => $this->getUrl('send/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'items' => array(
				$message,
				array(
					'title' => 'Uudiskiri',
					'type' => 'searchSelect',
					'name' =>  'newsletter',
					'maxElements' => 1,
					'allowAddingNew' => false,
					'selected' => array($item->newsletter->id=>$item->newsletter->name),
					'ajaxUrl' => $this->getUrl('searchNewsletters/[$search]'),
				),	
				array(
					'title' => 'List',
					'type' => 'searchSelect',
					'name' =>  'list',
					'maxElements' => 1,
					'allowAddingNew' => false,
					'selected' => array($item->list->id=>$item->list->name),
					'ajaxUrl' => $this->getUrl('searchEmailLists/[$search]'),
				),	
				array(
					'type' => 'dateTime',
					'title' => 'Algusaeg',
					'value' => $item->startTime,
					'name' => 'startTime',
				),
				array(
					'type' => 'checkBox',
					'title' => 'Kinnitatud',
					'checked' => $item->confirmed,
					'name' => 'confirmed',
				),
				array(
					'type' => 'textArea',
					'name' => 'comment',
					'value' => $item->comment,
					'title' => 'Kommentaar',
				),
			),
			'buttons' => array(
				array(
					'title' => 'Salvesta',
					'name' => 'save'
				),
				(!$item->confirmed ? null : array(
					'title' => 'Alusta saatmist',
					'name' => 'saveAndSend',
				)),
			),
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}

	public function sender( $id ) {

		$item = NewsletterSend::load( $id );
		
		$panel = array(
			'title' => 'Saatmine',
			'layout' => 'table',
			'style' => 'width:480px;',
			'bodyStyle' => 'padding:10px',
			'action' => $this->getUrl('sender/'.$id),
			'layoutConfig' => array(
				'columns' => 2,
				'columnWidths' => array( 150 ),
			),
			'html' => '
<script type="text/javascript">
var timeout = null;
function sendNext() {
	$("#sender").load("'.$this->getUrl('sendNext/'.$id).'", {}, function (responseText, textStatus, XMLHttpRequest) {
		if( responseText[0] != "&") {
  			timeout = setTimeout("sendNext()",2000);
  		} else {
			$("#stop").hide();
		}
	});
	$("#continue").hide();
	$("#stop").show();
}
function stopSender() {
	clearTimeout(timeout);
	alert("Saatmine peatatud!");
	$("#continue").show();
	$("#stop").hide();	
}
$(document).ready(function(){
	sendNext();
})
</script>

<div id="sender"></div>
<center>
<a href="javascript:stopSender()" id="stop" style="text-decoration:none;"><b style="color:red; font-size:15px;">Stop</b></a>
<a href="javascript:sendNext()" id="continue" style="text-decoration:none;"><b style="color:green; font-size:15px;">Jätka</b></a>
</center>',
		);
				
		$this->view->contents = DomFg::render( $panel );
		
	}
	
	public function sendNext( $id = NULL ) {
		$this->view->setTemplate(false);
		
		$item = NewsletterSend::load( $id );
		$item->sendNext();
		
		if( $item->sent+$item->errors < $item->max) {
			$timeLeftSeconds = ceil(($item->max-$item->sent-$item->errors)/NewsletterSend::SEND_MAILS_LIMIT) * 3;
			$timeLeftHours = (int)($timeLeftSeconds/3600);
			$timeLeftSeconds = $timeLeftSeconds%3600;
			$timeLeftMinutes = (int)($timeLeftSeconds/60);
			$timeLeftSeconds = $timeLeftSeconds%60;
			
			if( $timeLeftHours < 10 ) {
				$timeLeftHours = '0'.$timeLeftHours;
			}
			
			if( $timeLeftMinutes < 10 ) {
				$timeLeftMinutes = '0'.$timeLeftMinutes;
			}
			
			if( $timeLeftSeconds < 10 ) {
				$timeLeftSeconds = '0'.$timeLeftSeconds;
			}
			
			echo '
	Saatmine: <b>'.$item->newsletter->name.'</b> <br />
	List: <b>'.$item->list->name.'</b><br />
	<br />
	<div id="loader" style="padding:1px; margin:2px; border: 1px solid black; width:300px;">
		<div id="bar" style="width:'.(($item->sent+$item->errors) * 298 / $item->max).'px; height:7px; background-color:green;"></div>
	</div>
	Saadetud <b style="color:green">'.($item->sent+$item->errors).' / '.$item->max.'</b><br />
	Probleemseid emaile: <b style="color:red">'.$item->errors.'</b> <br />
	Aega jäänud: <b>'.$timeLeftHours.'h '.$timeLeftMinutes.'min '.$timeLeftSeconds.'s </b>
	<br /><br />
	<b style="color:red">Kui te antud akna sulgete jääb emailide saatmine pooleli.</b><br />
	(Emailide saatmist saab sellegipoolest hiljem samast kohast jätkata.)<br />
				';
		} else {
			echo '&nbsp;<b>Kõik emailid on saadetud!</b>';
		}
	}
		
	// ----------------------------------------------
	// Misc
	// ----------------------------------------------
	
	public function help() {
					
		$view = new DomView( '/'.Newsletter::ADMIN_TEMPLATES_DIR . 'help.html'  );

		$panel = array(
			'title' => 'Abi',
			'layout' => 'table',
			'bodyStyle' => 'padding:10px',
			'html' => $view->fetch(),
		);
				
		$this->view->contents  = DomFg::render( $panel );
	}
	
	public function setup() {
		$menu = array(
			'type' => 'menu',
			'items' => array(
				array(
					'title' => 'Uudiskirjad',	
					'link' => $this->getSiteUrl(''),
					'items' => array(
						array(
							'title' => 'Uudiskirjad',	
							'link' => $this->getSiteUrl('Newsletter/newsletters/'),
						),
						array(
							'title' => 'Listid',	
							'link' => $this->getSiteUrl('Newsletter/emailLists/'),
						),
						array(
							'title' => 'Saatmised',	
							'link' => $this->getSiteUrl('Newsletter/sends/'),
						),
						array(
							'title' => 'Abi',	
							'link' => $this->getSiteUrl('Newsletter/help/'),
						),
					),
				),
			),
		);
		$this->view->menu = DomFg::render( $menu );
	}

}
?>